
import 'dart:async';




/// stream 创建方案
void main(){
  print("main begin");
  // testFromFuture();
  // testFromFutures();
  // testFromIterable();
  testPeriodic1();
  // testPeriodic2();
  print("main begin");
}

Future<String> getData5(){

  return Future.delayed(Duration(seconds: 5),(){
    print("getData5...");
    return "getData5：${DateTime.now()}";
  });
}
Future<String> getData(){

  return Future((){
    print("getData...");
    return "getData：${DateTime.now()}";
  });
}

/// fromFuture 根据Future进行创建
void testFromFuture(){
  Stream stream = Stream.fromFuture(getData5());
  stream.listen((event) {
    print("event:$event");
  }).onDone(() {
    print("完成");
  });
  // Stream.fromFuture(getData5())
  //     .listen((event) {
  //       print("event:$event");
  //     })
  //     .onDone(() {
  //       print("done ");
  //     });
}

///根据多个Future创建
void testFromFutures(){
  //先执行完所有的Future，统一发送数据
  Stream.fromFutures([getData5(),getData(),getData()])
      .listen((event) {
        print("event-data:$event");
        print("event-data:${DateTime.now()}");
      })
      .onDone(() {
        print("done ");
      });
}

void testFromIterable(){
  var datas = [1,'hello',2,'he',5];
  Stream.fromIterable(datas)
      .listen((event) {
        print("event:$event");
      })
      .onDone(() {
        print("done ");
      });
}

void testPeriodic1(){
  Duration interval = Duration(seconds: 1);
  int i = 0;
  Stream.periodic(interval,(data)=> data + 2)
      .listen((event) {
        print("event:$event");
      })
      .onDone(() {
        print("done ");
      });
}

void testPeriodic2(){
  Duration interval = Duration(seconds: 2);
  int i = 0;
  //take(5) 指定最大提取
  Stream.periodic(interval,(data)=>data)
      .listen((event) {
        print("event:$event");
      })
      .onDone(() {
        print("done ");
      });
}